//
//  CRVideoViewController.m
//  NewAge
//
//  Created by dllo on 15/12/3.
//  Copyright © 2015年 ColorRevolution. All rights reserved.
//

#import "CRVideoViewController.h"
#import "CRMyCell.h"
#import "CRHeadMyCell.h"
#import "CRVideoModel.h"
#import "CRheadVideoController.h"
#import <MediaPlayer/MediaPlayer.h>
#import "UIImageView+LK.h"



@interface CRVideoViewController ()<UITableViewDelegate, UITableViewDataSource, UICollectionViewDataSource, UICollectionViewDelegate>

@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSMutableArray *arr;// 视频数组
@property(nonatomic, strong)UICollectionView *headCollectionView;
@property(nonatomic, strong)NSMutableArray *cArr;// 头部数组

@property(nonatomic, strong)MPMoviePlayerViewController *movieView;
@property (nonatomic, strong) NSIndexPath *indexPath;
@property (nonatomic, assign) CGRect selectedRect;

@property (nonatomic, assign) BOOL isFull;

@property(nonatomic, strong)UIButton *button;

@end

@implementation CRVideoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBar.translucent = NO;
    
    // Do any additional setup after loading the view.
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(jumpFullScreen) name:@"MPMoviePlayerWillEnterFullscreenNotification" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(exitFullScreen) name:@"MPMoviePlayerWillExitFullscreenNotification" object:nil];
    
    
    [self creatView];
    [self creatData];
    

}

- (void)viewWillDisappear:(BOOL)animated {
    if (!self.isFull) {
        if (self.movieView.view) {
            [self.movieView.view removeFromSuperview];
        }
    }
}

- (void)jumpFullScreen {
    
    self.isFull = YES;
    
}

- (void)exitFullScreen {
    self.isFull = NO;
}

#pragma mark - 创建TableView

- (void)creatView {
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.tableView.rowHeight = HEIGHT / 2;
    [self.view addSubview:self.tableView];
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    self.tableView.tableFooterView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    [self.tableView registerClass:[CRMyCell class] forCellReuseIdentifier:@"reuse"];
    
    // 1. 要创建collectionView, 将先创建一个flowLayout, 创建完之后才能创建collectionView
    
    // 它是苹果推荐使用的一个标准的瀑布流
    UICollectionViewFlowLayout *headFlowLayout = [[UICollectionViewFlowLayout alloc] init];
    
    // 设置item的大小, item就和tableView的row
    headFlowLayout.itemSize = CGSizeMake((WIDTH - 6) / 4,HEIGHT / 7 - 5);
    
    // 最小的列间距
    headFlowLayout.minimumInteritemSpacing = 2;
    
    // 创建collectionView
    
    self.headCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT / 7) collectionViewLayout:headFlowLayout];
    
    self.tableView.tableHeaderView = self.headCollectionView;
    
    // 默认背景是黑色
    self.headCollectionView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    // 签订代理人
    self.headCollectionView.dataSource = self;
    self.headCollectionView.delegate = self;
    
    // collectionView想要创建cell的话只能使用注册的方式
    
    [self.headCollectionView registerClass:[CRHeadMyCell class] forCellWithReuseIdentifier:@"reuse1"];
    
    
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(playbackStateChanged:)
//                                                 name:MPMoviePlayerPlaybackStateDidChangeNotification object:self.movieView];
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                            selector:@selector(mediaPlayerPlaybackStateChange:)
//                                                name:MPMoviePlayerPlaybackStateDidChangeNotification object:self.movieView];
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(mediaPlayerPlaybackFinished:)
//                                                 name:MPMoviePlayerPlaybackDidFinishNotification object:self.movieView];
}

- (void)addNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(mediaPlayerPlaybackStateChange:)
                                                 name:MPMoviePlayerPlaybackStateDidChangeNotification object:self.movieView];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(mediaPlayerPlaybackFinished:)
                                                 name:MPMoviePlayerPlaybackDidFinishNotification object:self.movieView];

}


- (void)mediaPlayerPlaybackStateChange:(NSNotification *)nsnotification {
    switch (self.movieView.moviePlayer.playbackState) {
        case MPMoviePlaybackStatePlaying: {
//            [self.hudTwo removeFromSuperview];
            NSLog(@"正在播放...");
        } break;
        case MPMoviePlaybackStatePaused:
            NSLog(@"暂停播放.");
            break;
        case MPMoviePlaybackStateStopped:
            NSLog(@"停止播放.");
            break;
        default:
            NSLog(@"播放状态:%li",(long)self.movieView.moviePlayer.playbackState);
            break;
    }
    
}

- (void)mediaPlayerPlaybackFinished:(NSNotification *)notfication {
    NSLog(@"播放完成.%li", (long)self.movieView.moviePlayer.playbackState);
    [self.movieView.moviePlayer stop];
    [self.movieView.moviePlayer pause];
    [self.movieView.view removeFromSuperview];
}
#pragma mark - 数据解析
- (void)creatData {
    [MBProgressHUDManager showHUDtoView:self.view string:@"加载中"];
    
    [AfNetWorkingManager getInfoWithUrl:@"http://c.m.163.com/nc/video/home/0-10.html" block:^(NSDictionary *resultDic, NSError *error) {
        
        self.arr = [NSMutableArray array];
        self.cArr = [NSMutableArray array];        
        
        self.arr = [CRVideoModel baseModelByArr:resultDic[@"videoList"]];
        
        self.cArr = [CRVideoModel baseModelByArr:resultDic[@"videoSidList"]];
        
        [self.tableView reloadData];
        [self.headCollectionView reloadData];
        
        [MBProgressHUDManager removeHUD];
        
    }];
    
}


#pragma mark - collectionView两个协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.cArr.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CRVideoModel *model = self.cArr[indexPath.item];
    CRHeadMyCell *twoCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse1" forIndexPath:indexPath];
    twoCell.contentView.backgroundColor = [UIColor whiteColor];
    twoCell.myLabel.text = model.title;
    [twoCell.myImageView sd_setImageWithURL:[NSURL URLWithString:model.imgsrc]];
    return twoCell;
}



#pragma mark - collectionView点击方法

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    CRVideoModel *model = self.cArr[indexPath.row];
    CRheadVideoController *headVC = [[CRheadVideoController alloc] init];
    headVC.sid = model.sid;
    NSLog(@"%@", headVC.sid);
    headVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:headVC animated:YES];
    
}

#pragma mark - tableView两个协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.arr.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CRVideoModel *model = self.arr[indexPath.row];
    CRMyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    
    cell.myLabel.text = model.title;
    [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:model.cover]];
    
    NSString *ss = [NSString stringWithFormat:@"%@", model.playCount];
    cell.twoLabel.text = model.descriptionVC;
    NSString *str = [model.ptime substringWithRange:NSMakeRange(11, 5)];
    cell.threeLabel.text = [NSString stringWithFormat:@"时间:%@      阅读量:%.1f万", str, [ss floatValue]/10000];
    // 点击cell时的颜色
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.myImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [cell.myImageView addGestureRecognizer:tap];
    
    // 点几下才能触发的方法
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    
    return cell;
    
    
}

#pragma mark - ImageView click method
- (void)tapAction:(UITapGestureRecognizer *)sender{
    if (self.movieView.view) {
    [self.movieView.view removeFromSuperview];
    }
    UIView *view = sender.view;
    UITableViewCell *cell = (UITableViewCell *)view.superview.superview;
    self.indexPath = [self.tableView indexPathForCell:cell];
    CRVideoModel *model = self.arr[self.indexPath.row];
    self.movieView = [[MPMoviePlayerViewController alloc]initWithContentURL:[NSURL URLWithString:model.mp4_url]];
    self.movieView.view.frame = CGRectMake(10, 75, [UIScreen mainScreen].bounds.size.width - 20, HEIGHT / 3 + 8);
    [self.movieView.moviePlayer setScalingMode:(MPMovieScalingModeAspectFit)];
    [self.movieView.moviePlayer setControlStyle:(MPMovieControlStyleEmbedded)];
    [cell addSubview:self.movieView.view];
    
    
    // 关闭按钮
    self.button = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.button addTarget:self action:@selector(close:) forControlEvents:UIControlEventTouchUpInside];
    [self.button setBackgroundImage:[UIImage imageNamed:@"iconfont-guanbi"] forState:UIControlStateNormal];
    [self.movieView.view addSubview:self.button];
    [self.button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.movieView.view).with.offset(-5);
        make.top.equalTo(self.movieView.view.mas_top).with.offset(5);
        make.width.mas_equalTo(20);
        make.height.mas_equalTo(20);
    }];
//    self.button.frame = CGRectMake(self.movieView.view.frame.size.width - 30, 10, 20, 20);
    
    
//

}
#pragma mark - scrollView
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CRMyCell *cell = (CRMyCell *)[self.tableView cellForRowAtIndexPath:self.indexPath];
    CGRect rectInTable = [self.tableView rectForRowAtIndexPath:self.indexPath];
    CGRect rectInWindow =[self.tableView convertRect:rectInTable toView:[self.tableView superview]];
    self.selectedRect = CGRectMake(rectInTable.origin.x + 10, rectInTable.origin.y + 75, cell.myImageView.bounds.size.width, cell.myImageView.bounds.size.height);
    if ([self.movieView.moviePlayer isPreparedToPlay]) {

        NSLog(@"%zi", [self.movieView.moviePlayer isPreparedToPlay]);
        if (rectInWindow.origin.y + HEIGHT / 2 < 0 || rectInWindow.origin.y > [UIScreen mainScreen].bounds.size.height-cell.myImageView.bounds.size.height) {
            [UIView animateWithDuration:0.5 animations:^{
                self.movieView.view.frame = CGRectMake(self.view.bounds.size.width-180, self.view.bounds.size.height-199, 170, 150);
                self.button.frame = CGRectMake(self.view.bounds.size.width - 180, self.view.bounds.size.height-199, 10, 10);
                [self.movieView.view addSubview:self.button];
                [self.view addSubview:self.movieView.view];

                self.movieView.moviePlayer.controlStyle = MPMovieControlStyleEmbedded;
            }];
            
        } else {
            self.movieView.view.frame = self.selectedRect;
            [self.tableView addSubview:self.movieView.view];
            self.movieView.moviePlayer.controlStyle = MPMovieControlStyleDefault;
            self.button.frame = CGRectMake(self.movieView.view.frame.size.width - 30, 10, 20, 20);
            
            
            [self.movieView.view addSubview:self.button];
            [self addNotification];
        }
        
    }
    
}

#pragma mark - button
- (void)close:(UIButton *)button {
    [self.movieView.moviePlayer stop];
    [self.movieView.moviePlayer pause];
    [self.movieView.view removeFromSuperview];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
